package com.mf.morefun.ui.myclass.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mf.morefun.R;
import com.mf.morefun.adapter.RankAdapter;
import com.mf.morefun.base.BaseBusFragment;
import com.mf.morefun.bean.ClassListBean;
import com.mf.morefun.bean.RankBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestRankBean;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.widget.NetErrorPop;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RankFragment extends BaseBusFragment {
    @BindView(R.id.tv_stars)
    TextView tvStars;
    @BindView(R.id.v_stars)
    View vStars;
    @BindView(R.id.ll_stars)
    LinearLayout llStars;
    @BindView(R.id.tv_flower)
    TextView tvFlower;
    @BindView(R.id.v_flower)
    View vFlower;
    @BindView(R.id.ll_flower)
    LinearLayout llFlower;
    @BindView(R.id.tv_certificate)
    TextView tvCertificate;
    @BindView(R.id.v_certificate)
    View vCertificate;
    @BindView(R.id.ll_certificate)
    LinearLayout llCertificate;
    @BindView(R.id.sp_type)
    Spinner spType;
    @BindView(R.id.v_rank)
    ViewPager vRank;
    private List<View> viewContains = new ArrayList<View>();//viewpager容器
    private List<String> mList = new ArrayList<>();
    private MyPagerAdapter myPagerAdapter;
    /*
    0 总榜
1 本月
2 上月
3 本周
4 上周
     */
    private int cycletype = 0;
    private ClassListBean mClassListBean;
    private String rankTypes[];

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_rank;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        changeButtonColor(0);
        Bundle args = getArguments();
        if (null != args) {
            mClassListBean = (ClassListBean) args.getSerializable("CLASSBEAN");
        } else {
            mClassListBean = new ClassListBean();
        }
        if (null != mClassListBean) {
            showViewPager();
        }
        rankTypes = getActivity().getResources().getStringArray(R.array.rank_type);
        ArrayAdapter<CharSequence> changeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.rank_type, R.layout.layout_myspinner);
        spType.setAdapter(changeAdapter);
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                vRank.removeAllViews();
                cycletype = position;
                changeButtonColor(0);
                showViewPager();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public static RankFragment newInstance(ClassListBean mClassListBean) {
        RankFragment newFragment = new RankFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("CLASSBEAN", mClassListBean);
        newFragment.setArguments(bundle);
        return newFragment;
    }

    private void showViewPager() {
        viewContains.clear();
        setPagerAdapter();
        setPagerListener();
        mList.clear();
        mList.add("星星数");
        mList.add("红花数");
        mList.add("奖状数");
        for (int i = 0; i < 3; i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_rank, null);
            TextView tv_type = view.findViewById(R.id.tv_type);
            tv_type.setText(mList.get(i));
            ListView lv_rank = view.findViewById(R.id.lv_rank);
            LinearLayout ll_all = view.findViewById(R.id.ll_all);
            initGetRankList(ll_all, tv_type, lv_rank, (i + 1));
            viewContains.add(view);
        }
        myPagerAdapter.notifyDataSetChanged();
    }

    private void initGetRankList(LinearLayout ll_all, TextView tv_type, ListView lv_rank, int type) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CLASSTOP);
        RequestRankBean requestRankBean = new RequestRankBean();
        requestRankBean.setClassId(mClassListBean.getClassBelong().getId());
        requestRankBean.setType(type);
        requestRankBean.setCycleType(cycletype);
        params.setBodyContent(JSON.toJSONString(requestRankBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean mResultBean = JSON.parseObject(result, ResultBean.class);
                    if (mResultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(mResultBean.getResult())) {
                            ll_all.setVisibility(View.VISIBLE);
                            List<RankBean> rankList = JSON.parseArray(mResultBean.getResult(), RankBean.class);
                            RankAdapter adapter = new RankAdapter(getActivity(), rankList);
                            lv_rank.setAdapter(adapter);
                        } else {
                            ll_all.setVisibility(View.GONE);
                        }
                    } else {
                        ll_all.setVisibility(View.GONE);
                        ToastUtils.show(getActivity(), mResultBean.getMessage(), 100);
                    }
                } else {
                    ll_all.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(getActivity());
                    errorPop.showPop("");
                    break;
            }
        }
    };

    private void setPagerListener() {
        vRank.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //
                changeButtonColor(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return viewContains.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//                ((ViewPager) container).removeView(viewContains.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position %= viewContains.size();
            if (position < 0) {
                position = viewContains.size() + position;
            }
            View view = viewContains.get(position);
            // 如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }


    private void setPagerAdapter() {
        myPagerAdapter = new MyPagerAdapter();
        vRank.setAdapter(myPagerAdapter);
    }

    private void changeButtonColor(int index) {
        switch (index) {
            case 0:
                tvStars.setTextColor(0xffffffff);
                vStars.setVisibility(View.GONE);
                llStars.setBackgroundResource(R.drawable.blue_bgshape);
                tvFlower.setTextColor(0xff666666);
                vFlower.setVisibility(View.GONE);
                llFlower.setBackgroundResource(R.drawable.line_blue);
                tvCertificate.setTextColor(0xff666666);
                vCertificate.setVisibility(View.GONE);
                llCertificate.setBackgroundResource(R.drawable.line_blue);
                break;
            case 1:
                tvStars.setTextColor(0xff666666);
                vStars.setVisibility(View.GONE);
                llStars.setBackgroundResource(R.drawable.line_blue);
                tvFlower.setTextColor(0xffffffff);
                vFlower.setVisibility(View.GONE);
                llFlower.setBackgroundResource(R.drawable.blue_bgshape);
                tvCertificate.setTextColor(0xff666666);
                vCertificate.setVisibility(View.GONE);
                llCertificate.setBackgroundResource(R.drawable.line_blue);
                break;
            case 2:
                tvStars.setTextColor(0xff666666);
                vStars.setVisibility(View.GONE);
                llStars.setBackgroundResource(R.drawable.line_blue);
                tvFlower.setTextColor(0xff666666);
                vFlower.setVisibility(View.GONE);
                llFlower.setBackgroundResource(R.drawable.line_blue);
                tvCertificate.setTextColor(0xffffffff);
                vCertificate.setVisibility(View.GONE);
                llCertificate.setBackgroundResource(R.drawable.blue_bgshape);
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.ll_stars, R.id.ll_flower, R.id.ll_certificate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_stars:
                vRank.setCurrentItem(0);
                break;
            case R.id.ll_flower:
                vRank.setCurrentItem(1);
                break;
            case R.id.ll_certificate:
                vRank.setCurrentItem(2);
                break;
        }
    }
}
